package com.lyjilu.web.servlet;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;

import com.lyjilu.model.entity.UploadFile;
import com.lyjilu.util.DaoUtil;
import com.lyjilu.util.UploadUtil;

/**
 * Servlet implementation class UploadSvt
 */
@WebServlet("/UploadSvt")
public class UploadSvt extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Default constructor.
	 */
	public UploadSvt() {
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		UploadFile uploadFile = null;
		UploadUtil upbase = new UploadUtil();
		try {
			uploadFile = upbase.parseRequest(request);
		} catch (Exception e) {
			e.printStackTrace();
			return;
		}

		for (Iterator<String> iterator = uploadFile.getFields().keySet()
				.iterator(); iterator.hasNext();) {
			String key = (String) iterator.next();
			System.out.println(key);
			Object obj = uploadFile.getFields().get(key);
			if (obj instanceof List) {
				for (Iterator<Object> iterator2 = ((List<Object>) obj)
						.iterator(); iterator2.hasNext();) {
					Object object1 = (Object) iterator2.next();
					System.out.println(object1);
				}
			} else {
				System.out.println(obj);
			}
		}
		doSomething1(uploadFile);
		doSomething2(uploadFile);
		doSomething3(uploadFile);
		request.getRequestDispatcher("download.jsp").forward(request, response);
	}

	/**
	 * 模拟上传文件存放到数据库，
	 * @param uploadFile 上传表达对象，保护文件几普通表单域
	 */
	private void doSomething1(UploadFile uploadFile) {
		String sql = "insert into file(name,size,cre_time,type,content,cre_user) values(?,?,?,?,?,?)";
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			conn = DaoUtil.getConn();
			for (Iterator<FileItem> iterator = uploadFile.getFiles().iterator(); iterator
					.hasNext();) {
				FileItem file = (FileItem) iterator.next();
				ps = conn.prepareStatement(sql);
				ps.setString(1, file.getName());
				ps.setLong(2, file.getSize());
				ps.setTimestamp(3,
						new java.sql.Timestamp(System.currentTimeMillis()));
				ps.setString(4, file.getContentType());
				ps.setBytes(5, file.get());
				ps.setString(6, (String) uploadFile.getFields().get("cre_user"));
				int result = ps.executeUpdate();
				System.out.println(result);
				ps.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DaoUtil.closeDao(null, ps, conn);
		}
	}

	/**
	 * 模拟讲文件存放到硬盘，
	 * @param uploadFile
	 */
	private void doSomething2(UploadFile uploadFile) {
		String PATH = "/";
		for (Iterator<FileItem> iterator = uploadFile.getFiles().iterator(); iterator
				.hasNext();) {
			FileItem file = (FileItem) iterator.next();
			InputStream input = null;
			OutputStream out = null;
			try {
				input = file.getInputStream();
				byte[] b = new byte[1024];
				String fileName = file.getName();
				out = new BufferedOutputStream(new FileOutputStream(PATH
						+ fileName));
				int i = 0;
				while ((i = input.read(b)) != -1) {
					out.write(b, 0, i);
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					out.flush();
				} catch (IOException e) {
					e.printStackTrace();
				}
				try {
					out.close();
				} catch (IOException e) {
					out = null;
				}
			}

		}

	}

	/**
	 * 模拟将文件存储到硬盘，并且讲文件路径存放到数据库
	 * @param uploadFile
	 */
	private void doSomething3(UploadFile uploadFile) {
		String PATH = "/";
		String sql = "insert into file(name,size,cre_time,type,content,cre_user,diskpath) values(?,?,?,?,?,?,?)";
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			conn = DaoUtil.getConn();
			for (Iterator<FileItem> iterator = uploadFile.getFiles().iterator(); iterator
					.hasNext();) {
				FileItem file = (FileItem) iterator.next();
				InputStream input = null;
				OutputStream out = null;
				String fileName = file.getName();
				String filePaht = PATH
						+ System.currentTimeMillis()
						+ (fileName.lastIndexOf(".") > -1 ? fileName
								.substring(fileName.lastIndexOf(".")) : "");
				try {
					input = file.getInputStream();
					byte[] b = new byte[1024];
					out = new BufferedOutputStream(new FileOutputStream(
							filePaht));
					int i = 0;
					while ((i = input.read(b)) != -1) {
						out.write(b, 0, i);
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					try {
						out.flush();
					} catch (IOException e) {
						e.printStackTrace();
					}
					try {
						out.close();
					} catch (IOException e) {
						out = null;
					}
				}
				ps = conn.prepareStatement(sql);
				ps.setString(1, file.getName());
				ps.setLong(2, file.getSize());
				ps.setTimestamp(3,
						new java.sql.Timestamp(System.currentTimeMillis()));
				ps.setString(4, file.getContentType());
				ps.setBytes(5, null);
				ps.setString(6, (String) uploadFile.getFields().get("cre_user"));
				ps.setString(7, filePaht);
				int result = ps.executeUpdate();
				System.out.println(result);
				ps.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DaoUtil.closeDao(null, ps, conn);
		}
	}

}
